"use server";
import { serverGlobal } from "@/utils/server_global";
import dayjs from "dayjs";
import fs from "fs";
import cron, { type ScheduledTask } from "node-cron";
import path from "path";

let timer: any = null;
const clearTask = () => {
  if (serverGlobal.taskIinstance) {
    serverGlobal.taskIinstance.stop();
    serverGlobal.taskIinstance.destroy();
    serverGlobal.taskIinstance = null;
  }
};
export const startTask = async () => {
  clearTask();

  serverGlobal.taskIinstance = cron.schedule("* * * * *", async () => {
    // 每隔一分钟检查一次
    const filePath = path.resolve("./", "time.txt");
    const now = dayjs().format("YYYY-MM-DD HH:mm:ss");
    fs.appendFileSync(filePath, now + "\n");
    // timer = setTimeout(() => {
    //   console.log("Running a task every minute");
    // }, 30000);
  });
  //   const result = await execSync(`pm2 start ${process.env.JSON_LOCATION}`);
  //   return result.toString("utf-8");
};

export const checkTask = async () => {
  if (serverGlobal.taskIinstance) {
    return true;
  } else {
    return false;
  }
};

export const stopTask = async () => {
  clearTask();
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
  //   const result = await execSync(`pm2 stop ${process.env.JSON_LOCATION}`);
  //   return result.toString("utf-8");
};
